package com.wang.android.library.tool;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * @author 杨满宇
 * @TODO: 2016/05/31  json解析工具类
 */
public class WJsonUtils {
//    private static Gson gson = new Gson();
    private static Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();

    public static <T> T object(String json, Class<T> classOfT) {

        return gson.fromJson(json, classOfT);
    }
    /**
     * obj转json
     * @param object
     * @return
     */
    public static String beanToJson(Object object) {
        Gson gson = new Gson();
        String json = gson.toJson(object);
        return json;
    }
    /**
     * 请求返回判断
     *
     * @param json
     * @return
     */
    public static String toObject(String json, String key) {
        String str = null;
        JSONObject jsonObject = null;
        if (json != null) {
            try {
                jsonObject = new JSONObject(json);
                str = jsonObject.get(key).toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return str;
    }


    public static <T> List<T> getList(String jsonString, Class<T> cls) {
        JsonElement root = new JsonParser().parse(jsonString);
        List<T> data = new ArrayList<T>();
        JsonArray rootArray = root.getAsJsonArray();
        for (JsonElement json : rootArray) {
            try {
                data.add(gson.fromJson(json, cls));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    public static <T> T getJsonBean(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;

    }


    public static Map<String, Object> getMapForJson(String jsonStr) {
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonStr);
            JSONArray jsonArray = new JSONArray();
            Iterator<String> keyIter = jsonObject.keys();
            String key = null;
            Object value;
            Map<String, Object> valueMap = new HashMap<String, Object>();
            while (keyIter.hasNext()) {
                key = keyIter.next();
                value = jsonObject.get(key);
                valueMap.put(key, value);
            }
            return valueMap;

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            Log.e("TAG", e.toString());
        }
        return null;
    }

    /**
     * Json 转成 List<Map<>>
     *
     * @param jsonStr
     * @return
     */
    public static List<Map<String, Object>> getlistForJson(String jsonStr) {

        List<Map<String, Object>> list = null;

        JSONObject jsonObj = null;

        try {
            JSONArray jsonArray = new JSONArray(jsonStr);
            list = new ArrayList<Map<String, Object>>();

            for (int i = 0; i < jsonArray.length(); i++) {

                jsonObj = (JSONObject) jsonArray.get(i);
                list.add(getMapForJson(jsonObj.toString()));
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return list;
    }

    /***
     * 获取JSON类型
     * 判断规则
     * 判断第一个字母是否为{或[ 如果都不是则不是一个JSON格式的文本
     *
     * @param str
     * @return
     */
    public static String getJSONType(String str) {
        if (TextUtils.isEmpty(str)) {
            return "error";
        }
        final char[] strChar = str.substring(0, 1).toCharArray();
        final char firstChar = strChar[0];
        if (firstChar == '{') {
            return "object";
        } else if (firstChar == '[') {
            return "array";
        } else {
            return "error";
        }
    }

    /**
     * null 过滤
     *
     * @param <T>
     */
    public static class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            Class<T> rawType = (Class<T>) type.getRawType();
            if (rawType != String.class) {
                return null;
            }
            return (TypeAdapter<T>) new StringNullAdapter();
        }
    }


    public static class StringNullAdapter extends TypeAdapter<String> {
        @Override
        public String read(JsonReader reader) throws IOException {
            // TODO Auto-generated method stub
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return "";
            }
            return reader.nextString();
        }
        @Override
        public void write(JsonWriter writer, String value) throws IOException {
            // TODO Auto-generated method stub
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }
}
